const fs = require("fs");
const path = require("path");
const SpaceService = require("../service/SpaceService");
const config = require("@/config/index");
const response = require("../utils/response");
const { nextId } = require("../utils/genrate_nextId");
// const writeLog = require("../utils/writeLog");
class AdminController {
  /**
   * 查询文件空间列表
   * @param {Context} ctx
   */
  async getSpaceList(req, res, next) {
    try {
      const result = await SpaceService.getSpaceList();
      res.json(response.success(result, "查询文件列表成功", 200));
    } catch (error) {
      next(error);
    }
  }

  /**
   * 新增数据
   * @param {Context} ctx
   */
  async addSpace(req, res, next) {
    try {
      const { spaceName } = req.body;
      const isHaveSpace = await SpaceService.getSpaceInfo(spaceName);
      console.log(isHaveSpace);
      if (isHaveSpace.length) {
        res.json(response.error(`新增文件空间已存在！`, isHaveSpace, 200));
        return;
      }
      const spaceId = nextId();
      const result = await SpaceService.addSpace([spaceId, spaceName], () => {
        return fs.mkdirSync(path.join(config.fileStorageDir, spaceId));
      });
      res.json(response.success(result, "success", 200));
    } catch (error) {
      next(error);
    }
  }

  /**
   * 更新文件空间数据
   * @param {Context} ctx
   */
  updateSpace(req, res, next) {
    try {
      const { spaceName, spaceId } = req.body;
      SpaceService.updateSpaceInfo({
        spaceName,
        spaceId,
      })
        .then((result) => {
          res.json(response.success(null, "success", 200));
        })
        .catch((err) => {
          res.json(response.error(err.code, null, err.errno));
        });
    } catch (error) {
      next(error);
    }
  }

  /**
   * 删除文件空间
   * @param {Context} ctx
   */
  deleteSpace(req, res, next) {
    try {
      const { spaceId } = req.query;
      SpaceService.deleteSpace(spaceId)
        .then(() => {
          res.json(response.success(null, "success", 200));
        })
        .catch((err) => {
          res.json(response.error(err.code, null, err.errno));
        });
    } catch (error) {
      next(error);
    }
  }
}
module.exports = new AdminController();
